﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using System.Threading;
using Odyssey.Effects;
using System.ComponentModel;

namespace Odyssey.Behaviors
{
    public abstract class PageEffectAction<E> : TriggerAction<PhoneApplicationPage> where E : PageEffect
    {
        private bool isActive;
        protected E Effect { get; private set; }

        public PageEffectAction()
            : base()
        {
            Effect = Activator.CreateInstance<E>();
        }

        public TimeSpan Duration
        {
            get { return Effect.Duration; }
            set { Effect.Duration = value; }
        }

        protected override void Invoke(object parameter)
        {
            if (!isActive)
            {
                isActive = true;
                PhoneApplicationPage page = AssociatedObject;
                Effect.Page = page;

                RoutedEventHandler eh = null;
                eh = (s, e) =>
                {
                    isActive = false;
                    page.Loaded -= eh;

                    Effect.IsActive = false;
                };
                page.Loaded += eh;

                page.UpdateLayout();
                Effect.IsActive = true;
                Thread.Sleep(0);
            }
        }

        /// <summary>
        /// Occurs after the storyboard completed activation.
        /// </summary>
        public event EventHandler Activated
        {
            add { Effect.Activated += value; }
            remove { Effect.Activated -= value; }
        }

        /// <summary>
        /// Occurs after the storyboard completed deactivation.
        /// </summary>
        public event EventHandler Deactivated
        {
            add { Effect.Deactivated += value; }
            remove { Effect.Deactivated -= value; }
        }

    }
}
